<?php

class HandlersController extends AppController {
    
    var $name = "Handlers";
    var $uses = array('Handler','Users');
    var $paginate = array(
        'Handler' => array(
            'limit' => 25,
            'order' => array('country', 'name')
        )
    );
    
    function beforeFilter() {
        if( $this->action != "admin_login" && $this->action != "admin_logout") {
            if ($this->Session->check('user') == false) {
                $this->redirect('/admin/users/login/');
            }
        }
    }
    
    public function admin_index() {
        $this->Handler->recursive = -1;
        $this->set('handlers', $this->paginate('Handler'));
    }
    
    public function admin_add() {
        $this->autoLayout = false;
        
        if( $this->RequestHandler->isAjax() ) {
            if( isset($_POST['data']) ) {
                $this->Handler->create($_POST['data']['Handler']);
                $data = $this->Handler->save();
                echo json_encode($data);
            }
        }
    }
    
    public function admin_edit($id = NULL) {
        
        if( $this->RequestHandler->isAjax() ) {
            if( isset($_POST['data']) ) {
                $this->autoRender = false;
                
                $this->Handler->id = $_POST['data']['Handler']['id'];
                $data = $this->Handler->save($_POST['data']['Handler']);
                
                echo json_encode($data);
                
                return;
            }
        }
        
        if( $id != NULL ) {
            $handler = $this->Handler->find('first', array('conditions' => array('Handler.id' => $id), 'recursive' => -1));
            $this->set('handler', $handler);
        }
    }
    
    /**
     * Deletes the Handler with the specified records from the system
     * 
     * @param int $id 
     */
    public function admin_delete($id) {
        $this->Handler->id = $id;
        $this->Handler->delete();
        
        if( !$this->RequestHandler->isAjax() ) {
            $this->redirect("/admin/handlers/");
        }
    }
    
    function admin_delete_selected() {

        if ($this->RequestHandler->isAjax()) {
            $this->autoRender = false;

            $this->Handler->deleteAll(array('Handler.id' => explode(",", $_POST['ids'])));
        }
    }
    
    function admin_details($handler_id) {
        $handler = $this->Handler->find('first', array(
            'conditions' => array('Handler.id' => $handler_id)
        ));
        
        $this->set('handler', $handler);
    }
    
    function admin_list() {
        $handlers = $this->paginate('Handler', array(
            $_POST['term'] . " LIKE" => '%' . $_POST['field'] . "%"
        ));
        
        $this->set('handlers', $handlers);
    }
}
?>
